package com.by.service.impl;

import com.by.bean.Supplier;
import com.by.bean.User;
import com.by.bean.UserType;
import com.by.common.crud.BaseServiceImpl;
import com.by.common.ex.BusinessException;
import com.by.common.utils.Assert;
import com.by.mapper.SupplierContactMapper;
import com.by.mapper.SupplierMapper;
import com.by.mapper.UserMapper;
import com.by.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SupplierServiceImpl extends BaseServiceImpl<Supplier, SupplierMapper> implements SupplierService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    SupplierContactMapper supplierContactMapper;

    @Override
    public int save(Supplier entity) {
        //检查用户是否存在
        int c=userMapper.queryUserByUserName(entity.getAccount());
        if(c>0)
            throw new BusinessException("该账号已存在！");
        //保存用户
        User user=new User(entity.getAccount(),entity.getPassword(), UserType.SUPPLIER_USER);
        int rs=userMapper.save(user);
        Assert.isZero(rs,"供应商用户保存失败");

        //设置连接人的供应商id
        entity.getContact().setSupplierId(user.getId());
        //保存供应商联系人
        rs=supplierContactMapper.save(entity.getContact());
        Assert.isZero(rs,"保存供应商联系人失败");
        //设置供应商id
        entity.setId(user.getId());
        return super.save(entity);
    }
}
